package com.yx.demo

import android.graphics.Bitmap
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ImageSpan
import android.view.View
import androidx.databinding.DataBindingUtil
import com.cloud.idcard.IdCardReader
import com.cloud.idcard.ReadIdCardListener
import com.cloud.idcard.UsbIdCardReader
import com.yecontech.library_card.IDCard
import com.yx.demo.databinding.ActivityIdCardBinding


class IdCardActivity : BaseActivity() {

    private lateinit var binding: ActivityIdCardBinding
    private lateinit var idCardReaderDk : IdCardReader
    private lateinit var soundManager: SoundManager

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_id_card)

        idCardReaderDk = UsbIdCardReader()
        idCardReaderDk.init(context)

        soundManager = SoundManager(context)
        binding.clear.setOnClickListener { binding.textView.text = "" }
    }

    override fun onResume() {
        super.onResume()
        idCardReaderDk.start(readIdCardListener)
    }

    override fun onPause() {
        super.onPause()
        idCardReaderDk.stop()
    }

    override fun onDestroy() {
        super.onDestroy()
        idCardReaderDk.close()
        soundManager.release()
    }

    private val readIdCardListener: ReadIdCardListener = object: ReadIdCardListener{
        override fun onProgress(progress: Int) {

        }

        override fun onReadCarSn(cardSn: String?) {
            soundManager.playBeep()
            appendCard(cardSn)
        }

        override fun onReadIdCard(idCard: IDCard?) {
            soundManager.playBeep()
            appendCard(idCard.toString())
            appendIdCardImage(idCard?.photo)
        }

        override fun onError(exception: RuntimeException?) {
            appendCard(exception?.message)
        }
    }

    private fun appendCard(cardNo: String?) {
        handler.post {
            if (binding.textView.length() > 10240) {
                binding.textView.text = ""
            }
            binding.textView.append(cardNo)
            binding.textView.append("\r\n")
            binding.scrollView.fullScroll(View.FOCUS_DOWN)
        }
    }

    private fun appendIdCardImage(bitmap: Bitmap?) {
        bitmap?.let {
            handler.post {
                val span = ImageSpan(context, bitmap)
                val spanStr = SpannableString(" ")
                spanStr.setSpan(span, 0, spanStr.length, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
                binding.textView.append(spanStr)
                binding.textView.append("\n\n")
                binding.scrollView.fullScroll(View.FOCUS_DOWN)
            }
        }
    }
}